import pycurl
import time
import sys
import socket
import re


class culjc:
    def __init__(self):
        self.contents = 'download.file'
        self.fp = open(self.contents, 'wb+')
        self.c = pycurl.Curl()
        self.c.setopt(pycurl.WRITEFUNCTION, self.bd_callback)
        self.c.setopt(pycurl.MAXREDIRS, 5)


    def bd_callback(self,buff):
        self.fp.write(buff)


    def start(self,url):
        try:
            self.c.setopt(pycurl.URL, url)
            self.c.perform()
            http_code = self.c.getinfo(pycurl.HTTP_CODE)
            dns_resolve = self.c.getinfo(pycurl.NAMELOOKUP_TIME)
            http_conn_time = self.c.getinfo(pycurl.CONNECT_TIME)
            http_speed_downlaod = self.c.getinfo(pycurl.SPEED_DOWNLOAD)
            ip = self.getIp(url)
            # result = url+"   IP:"+ip+"   响应状态:"+str(http_code)+"   建立连接时间:"+str(http_conn_time)+" ms   平均下载速度:"+str(http_speed_downlaod/1024)+" k/s"
            result = {'url':url,'ip':ip,'status':http_code,'con':round(http_conn_time,5),'sd':round(http_speed_downlaod/1024,2)}
            return result
        except Exception as e:
            result = "url:"+url+"   error:"+e


    def getIp(self,domain):
        domain1 = re.compile(r'^http:\/\/([a-zA-Z0-9\.]+)', re.S)
        d = re.findall(domain1, domain)[0]
        try:
            myaddr = socket.getaddrinfo(d, 'http')[0][4][0]
            return myaddr
        except Exception as e:
            return '0.0.0.0'





